import pdb
from pymysql.err import IntegrityError

#数据库查询操作
def conn_select(sql, curr):
    try:
        curr.execute(sql)
        result = curr.fetchall()
        return result
    except Exception as e:
        print("-"*10+f"数据库查询失败！{e}"+"-"*10)
        return "重连"

#数据库查询操作
def conn_select_all_col(conn, db):
    try:
        conn.execute("select * from %s limit 1 " % (db))
        result = [tuples[0] for tuples in conn.description]
        return result
    except:
        print("-"*10+"数据库查询失败！"+"-"*10)
        return "重连"


#数据库更新操作
def conn_update(sql, curr, conn):
    try:
        curr.execute(sql)
        conn.commit()
        return True
    except Exception as err:
        print(err)
        return "重连"

#数据库插入数据操作
def conn_insert(sql, data, curr, conn):
    try:
        if not data:
            curr.execute(sql)
        else:
            curr.execute(sql, data)
        conn.commit()
        Tid = curr.lastrowid
        return Tid
    except IntegrityError as e:
        print("数据已存在",e)
        return True
    except:
        print(sql)
        print(data)
        print("-" * 10 + "插入数据失败！" + "-" * 10)
        return "重连"

#数据库插入数据操作
def conn_insert_many(sql, data, curr, conn):
    try:
        curr.executemany(sql, data)
        conn.commit()
        return True
    except IntegrityError as e:
        print("数据已存在",e)
        return True
    except Exception as err:
        print(err)
        print(sql)
        print(data)
        print("-" * 10 + "插入数据失败！" + "-" * 10)
        return "重连"


#数据库删除操作
def conn_delete(sql, curr, conn):
    try:
        curr.execute(sql)
        conn.commit()
        return True
    except :
        print("-" * 10 + "删除数据失败！" + "-" * 10)
        return "重连"

